package com.ms.rc_lab;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class TcpClient {
    private final String SERVER_IP = "192.168.4.1";
    private final int SERVER_PORT = 8080;
    private static final int RECONNECT_DELAY = 1000; // 重连延迟时间（毫秒）
    private static TcpClient instance;
    private Socket socket;
    private boolean running;
    private OutputStream outputStream;
    private BufferedReader bufferedReader;
    private Thread receiveThread;
    private TcpClientListener listener;
    private ExecutorService sendThreadPool =  Executors.newSingleThreadExecutor();

    // 私有化构造函数
    private TcpClient() {
        socket = new Socket();
        running = false;
    }

    // 提供全局访问点
    public static synchronized TcpClient getInstance() {
        if (instance == null) {
            instance = new TcpClient();
        }
        return instance;
    }

    // 设置监听器
    public void setListener(TcpClientListener listener) {
        this.listener = listener;
    }

    // 接收消息的线程
    private void startReceiveThread() {
        receiveThread = new Thread(() -> {
            while (running) {
                try {
                    String message = bufferedReader.readLine();
                    if (message != null && listener != null) {
                        listener.onMessageReceived(message);
                    } else {
                        // 服务器断开连接
                        running = false;
                        reconnect(); // 尝试重连
                    }
                } catch (IOException e) {
                    running = false;
                    reconnect(); // 尝试重连
                }
            }
        });
        receiveThread.start();
    }

    // 启动客户端并尝试连接服务器
    public void start() {
        running = true;
        connect();
    }

    // 连接服务器
    private void connect() {

        new Thread(() -> {
            while (!socket.isConnected()) {
                Log.d("javer", "reconnect try");
                try {
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), 1000);
                    outputStream = socket.getOutputStream();
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    if (listener != null) {
                        listener.onConnectionStatusChanged(true);
                    }

                    // 开始接收消息
                    startReceiveThread();

                } catch (IOException e) {
                    // 连接失败
                    if (listener != null) {
                        listener.onConnectionFailed();
                    }
                    try {
                        // 等待后重试
                        Thread.sleep(RECONNECT_DELAY);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }).start();
    }

    // 重新连接
    private void reconnect() {
        closeConnection();
        connect();
    }

    // 关闭连接
    private void closeConnection() {
        running = false;
        try {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
            socket = new Socket();
            if (listener != null) {
                listener.onConnectionStatusChanged(false);
            }
        } catch (IOException e) {
            // 忽略关闭时的异常
        }
    }

    // 发送消息到服务器
    public void sendMessage(String message) {
        sendThreadPool.execute(() -> {
            if (socket.isConnected() && outputStream != null) {
                try {
                    outputStream.write(message.getBytes());
                    outputStream.flush();
                } catch (IOException e) {
                    reconnect();
                }
            }
        });
    }

    // 断开连接
    public void stop() {
        running = false;
        closeConnection();
        if(receiveThread != null) {
            receiveThread.interrupt();
        }
    }

    // 查询连接状态
    public boolean isConnected() {
        return socket != null && socket.isConnected() && !socket.isClosed();
    }

    // TCP客户端监听器接口
    public interface TcpClientListener {
        void onMessageReceived(String message);
        void onConnectionStatusChanged(boolean isConnected);
        void onConnectionFailed();
    }
}